package org.jeecg.modules.aliyun.entity.run;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.core.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.oss.entity.OssFile;
import org.jeecg.modules.oss.mapper.OssFileMapper;
import org.jeecg.modules.phone.entity.*;
import org.jeecg.modules.phone.enums.EntityEnums;
import org.jeecg.modules.phone.enums.TaskEnums;
import org.jeecg.modules.phone.mapper.*;
import org.jeecg.modules.system.util.FingerPrint;
import org.jeecg.modules.system.util.ImageUtils;
import org.jeecg.modules.system.util.PhotoDigest;
import org.jetbrains.annotations.NotNull;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static org.jeecg.modules.system.util.PhotoDigest.getData;


public class TaskUtil   {



    static PhoneEntityMapper phoneEntityMapper = SpringContextUtil.getBean(PhoneEntityMapper.class);
    static PhoneEntityCmdMapper phoneEntityCmdMapper = SpringContextUtil.getBean(PhoneEntityCmdMapper.class);

    public static void cmdBy4G(PhoneEntityTask phoneEntityTask, String cmdStr) {

        if (checkEntityStatusIsRunning(phoneEntityTask)) return;   /*执行中才给继续执行。*/

        boolean cmdRunning =  doCmdRun(phoneEntityTask.getEntityId(), cmdStr );

        if(!cmdRunning){
            /*超时了，需要定义为异常*/
            updateThis2CompletedorFail(phoneEntityTask, TaskEnums.TaskStatus.FAIL.getName());
        }
    }

    private static boolean checkEntityStatusIsRunning(PhoneEntityTask phoneEntityTask) {
        PhoneEntity phoneEntity1 = phoneEntityMapper.selectById(phoneEntityTask.getEntityId());
        System.out.println("手机状态" + phoneEntity1.getEntityStatus());
        if(!phoneEntity1.getEntityStatus().equals(EntityEnums.EntityStatus.RUNNING.getName())){
            System.out.println("手机状态不对" + phoneEntity1.getEntityStatus());
            return true;
        }
        return false;
    }

    static boolean doCmdRun(String entityId, String cmdStr) {

        PhoneEntityCmd phoneEntityCmd = new PhoneEntityCmd().setEntityId(entityId)
                .setCmdStatus("1").setCmdStr(cmdStr);
        phoneEntityCmdMapper.insert(phoneEntityCmd);
        System.out.println("插入数据库：" + cmdStr);
        System.out.println(phoneEntityCmd.getId());

        int count = 1;   /*命令2分钟内不执行就超时为异常了。*/
        while (count < 120) {
            sleepSecond(1,"命令执行中-----"+count+++"-----------" + cmdStr);
            PhoneEntityCmd phoneEntityCmd1 = phoneEntityCmdMapper.selectById(phoneEntityCmd.getId());
            if(phoneEntityCmd1.getCmdStatus().equals("0")){
                count = 1000 ;
                System.out.println("------执行了----------：" + cmdStr);
            }
            phoneEntityCmdMapper.updateById(new PhoneEntityCmd().setId(phoneEntityCmd1.getId()).setUpdateTime(new Date()));
        }

        System.out.println("------执行了tf----------：" + (count==1000));
        return  count==1000;
    }


    public static    void sleepSecond(int n) {
        sleepSecond(n,"");
    }




    public static void sleepSecond(int n, String msg) {
        try {
            System.out.println(msg);
            Thread.sleep(1000*n);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }



    public static void saveScreen(PhoneEntityTask phoneEntityTask, String fileName) {
        cmdBy4G(phoneEntityTask,"screencap -p /sdcard/" + fileName);
        cmdBy4G(phoneEntityTask,"smallSdcardPng" + fileName);
        cmdBy4G(phoneEntityTask,"uploadFileToServer" + fileName);
    }

    @NotNull
    private static String getOssFiles(String ScreenCapFile) {
        String returnFileName = "";
        OssFileMapper ossFileMapper = SpringContextUtil.getBean(OssFileMapper.class);

        int count = 1;
        while (count < 11) {
            System.out.println("Count is: "+ count + "," + ScreenCapFile); count++;
            sleepSecond(3,"检查截图中----------------");
            List<OssFile> list = ossFileMapper.selectList(new QueryWrapper<OssFile>().lambda()
                    .like(OssFile::getFileName, ScreenCapFile)
                    .orderByDesc(OssFile::getCreateTime).last("limit 1")
            );
            if(list.size()>0){
                count = 100 ;
                returnFileName = list.get(0).getUrl();
            }
        }
        if(count < 11){

        }
        return returnFileName;
    }



    private static void updateThis2CompletedorFail(PhoneEntityTask phoneEntityTask, String taskStatus) {

        PhoneEntityTaskMapper phoneEntityTaskMapper = SpringContextUtil.getBean(PhoneEntityTaskMapper.class);
        phoneEntityTask.setTaskStatus(taskStatus);
        phoneEntityTaskMapper.updateById(phoneEntityTask);

        if(taskStatus.equals(TaskEnums.TaskStatus.FAIL.getName())){
            PhoneEntityMapper phoneEntityMapper = SpringContextUtil.getBean(PhoneEntityMapper.class);
            PhoneEntity phoneEntity = phoneEntityMapper.selectById(phoneEntityTask.getEntityId());
            phoneEntity.setEntityStatus(EntityEnums.EntityStatus.WARN.getName());
            phoneEntityMapper.updateById(phoneEntity);
            PhoneEntityCmdMapper phoneEntityCmdMapper = SpringContextUtil.getBean(PhoneEntityCmdMapper.class);
            phoneEntityCmdMapper.update(new PhoneEntityCmd().setCmdStatus("0"),new QueryWrapper<PhoneEntityCmd>()
                    .lambda().eq(PhoneEntityCmd::getEntityId,phoneEntity.getId())
            );
            System.out.println("----------更新" + phoneEntity.getId() + "为异常");
        }
    }







    public static    void checkPointJob(PhoneEntityTask phoneEntityTask , String taskChildrenId ,Integer seq ) {

        System.out.println("---------------------开始检查断点Job---------");
        if (checkEntityStatusIsRunning(phoneEntityTask)) return;   /*执行中才给继续执行。*/
        String ScreenCapFile = "screen_" + phoneEntityTask.getEntityId() + RandomUtil.randomString(8) + ".png";
        saveScreen(phoneEntityTask,ScreenCapFile);

        /*获取截图*/
        String ScreenCapFile1 = getOssFiles(ScreenCapFile);
        /*获取对比图原图*/
        PhoneTaskChildrenMapper  phoneTaskChildrenMapper = SpringContextUtil.getBean(PhoneTaskChildrenMapper.class);
        PhoneTaskChildren phoneTaskChildren = phoneTaskChildrenMapper.selectById(phoneEntityTask.getTaskChildrenId());
        String ContrastImg2 = phoneTaskChildren.getTag();

//        String dir = "D://" ;
        String dir = "//app//tmp//" ;
        float percent = 0 ;
        System.out.println("ScreenCapFile1");
        System.out.println(ScreenCapFile1);
        System.out.println("ContrastImg2");
        System.out.println(ContrastImg2);
        if(!StringUtils.isEmpty(ScreenCapFile1) && !StringUtils.isEmpty(ContrastImg2)  ){
            String rnd1 = dir+RandomUtil.randomString(6)+".jpg" ;
            String rnd2 = dir+RandomUtil.randomString(6)+".jpg" ;
            ImageUtils.downLoadImg("https://ylphone.oss-cn-hangzhou.aliyuncs.com/upload/2022/09/fniaqc5re94pldq.png",rnd1);
            ImageUtils.downLoadImg("https://ylphone.oss-cn-hangzhou.aliyuncs.com/upload/2022/09/ftbnopmjpza5rjx.png",rnd2);
//            percent = PhotoDigest.compare(getData(rnd1),getData(rnd2));
            FingerPrint fp1 = null;
            FingerPrint fp2 = null;
            try {
                fp1 = new FingerPrint(ImageIO.read(new File(rnd1)));
                fp2 = new FingerPrint(ImageIO.read(new File(rnd2)));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
              percent = fp1.compare(fp2) * 100 ;
        }
        System.out.println("对比结果百分比：" + percent);
        if(percent > 80){
            updateThis2CompletedorFail(phoneEntityTask,TaskEnums.TaskStatus.COMPLETED.getName());
        }else{
            updateThis2CompletedorFail(phoneEntityTask,TaskEnums.TaskStatus.FAIL.getName());
        }
    }

}